package com.briup.run.web.filter;

import com.briup.run.util.IpUtil;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;

/**
 * @Auther: vanse(lc))
 * @Date: 2022/10/11-10-11-11:18
 * @Description：拦截访问 必定访问的资源
 */
@WebFilter("/member/activity.jsp")
public class AccessRecordFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        // 1.获取远程ip地址
        String ip = IpUtil.getIpAddr(request);
        // 2.和数据库比对 取出application的值判断
        ServletContext appliction = req.getServletContext();
        // 将来入库map
        Map<String, Long> map = (Map<String, Long>) appliction.getAttribute("map");
        Map<String, Long> result = (Map<String, Long>) appliction.getAttribute("result");
        if(map.containsKey(ip)){
            // 2.1 重复
            map.put(ip,map.get(ip)+1);
        }else{
            // 2.2 不重复
            map.put(ip,1L);
        }
        // 总访问人数 多少ip
        result.put("totalVisitor",Long.valueOf(map.size()));
        // 总访问量
        long totalCount= 0;
        for (Map.Entry<String, Long> entry : map.entrySet()) {
            // 所有的value相加
            totalCount += entry.getValue();
        }
        result.put("totalCount",totalCount);

        appliction.setAttribute("result",result);
        // 存最新的map 每2小时入库
        appliction.setAttribute("map",map);
        // 放行代码
        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
